package loginuser

import (
	"strings"

	"gitee.com/tomatomeatman/golang-repository/bricks/model/emity"
	"gitee.com/tomatomeatman/golang-repository/bricks/utils/gorm"
	Log "github.com/cihub/seelog"
)

type LoginUserDao struct {
}

// 修改密码
func (dao LoginUserDao) EditPass(sDbName, sId, sNewPass, sOldPass, sModifieder, sOwner string, iVersion int64) *emity.MsgEmity {
	txt := `
UPDATE ${BricksBaseSystem}LoginUser SET
	sPass = @sNewPass,
	dModifiedDate = NOW(),
	sModifieder = @sModifieder,
	iVersion = iVersion +1
WHERE sId = @sId
AND sPass = @sOldPass
AND iVersion = @iVersion`
	txt = strings.Replace(txt, "${BaseSystem}LoginUser", sOwner, -1)

	where := map[string]interface{}{
		"sId":         sId,
		"sModifieder": sModifieder,
		"sNewPass":    sNewPass,
		"sOldPass":    sOldPass,
		"iVersion":    iVersion,
	}

	dbResult := gorm.Exec(txt, where)
	if dbResult.Error != nil {
		Log.Error("更新数据发生异常:", dbResult.Error)
		return emity.MsgEmity{}.Err(7001, "更新数据发生异常:", dbResult.Error)
	}

	if 1 > dbResult.RowsAffected {
		return emity.MsgEmity{}.Err(7002, "数据没有影响值！")
	}

	return emity.MsgEmity{}.Success(7999, "更新成功")
}

// 重置密码
func (dao LoginUserDao) ResetPass(sDbName, sId, sNewPass, sModifieder, sOwner string, iVersion int64) *emity.MsgEmity {
	txt := `
UPDATE ${BricksBaseSystem}LoginUser SET
	sPass = @sNewPass,
	dModifiedDate = NOW(),
	sModifieder = @sModifieder,
	iVersion = iVersion +1
WHERE sId = @sId
AND iVersion = @iVersion`
	txt = strings.Replace(txt, "${BaseSystem}LoginUser", sOwner, -1)

	where := map[string]interface{}{
		"sId":         sId,
		"sModifieder": sModifieder,
		"sNewPass":    sNewPass,
		"iVersion":    iVersion,
	}

	dbResult := gorm.Exec(txt, where)
	if dbResult.Error != nil {
		Log.Error("更新数据发生异常:", dbResult.Error)
		return emity.MsgEmity{}.Err(7001, "更新数据发生异常:", dbResult.Error)
	}

	if 1 > dbResult.RowsAffected {
		return emity.MsgEmity{}.Err(7002, "数据没有影响值！")
	}

	return emity.MsgEmity{}.Success(7999, "更新成功")
}

// 根据用户编号设置用户类型
func (dao LoginUserDao) EditUserType(sDbName, sId, sType, sOwner string) *emity.MsgEmity {
	txt := `UPDATE ${BricksBaseSystem}LoginUser SET sType = @sType WHERE sId = @sId`
	txt = strings.Replace(txt, "${BaseSystem}LoginUser", sOwner, -1)

	where := map[string]interface{}{
		"sId":   sId,
		"sType": sType,
	}

	dbResult := gorm.Exec(txt, where)
	if dbResult.Error != nil {
		Log.Error("更新数据发生异常:", dbResult.Error)
		return emity.MsgEmity{}.Err(7001, "更新数据发生异常:", dbResult.Error)
	}

	if 1 > dbResult.RowsAffected {
		return emity.MsgEmity{}.Err(7002, "数据没有影响值！")
	}

	return emity.MsgEmity{}.Success(7999, "更新成功")
}
